<template>
  <view class="login-container">
    <!-- 标题 -->
    <view class="login-title">欢迎登录虾塘养殖系统</view>
    
    <!-- 描述文字 -->
    <view class="login-desc">请输入手机号完成登录</view>
    
    <!-- 登录表单 -->
    <view class="form-container">
      <!-- 手机号输入框 -->
      <view class="input-item">
        <input 
          type="number" 
          v-model="phone" 
          placeholder="请输入手机号"
          maxlength="11"
          @input="checkPhoneFormat"
          class="phone-input"
        />
      </view>
    </view>
    
    <!-- 登录按钮 -->
    <button 
      class="login-btn" 
      :disabled="!canLogin || isLoading"
      @click="submitLogin"
    >
      {{ isLoading ? '登录中...' : '登录' }}
    </button>
    
    <!-- 加载提示 -->
    <view v-if="isLoading" class="loading">处理中...</view>
  </view>
</template>

<script>
import { getWxLoginCode } from '../../utils/auth.js'
import {login} from "../../api/login";

export default {
  data() {
    return {
      phone: '', // 手机号
      isLoading: false,
      canLogin: false, // 手机号格式是否正确
      code: '' // 存储登录code
    }
  },
  
  onLoad() {
    // 检查是否已登录
    const accessToken = uni.getStorageSync('accessToken')
    const accessExpiresIn = Number(uni.getStorageSync('accessExpiresIn'))
    
    // 检查token是否存在且未过期
    if (accessToken && accessExpiresIn) {
      const currentTime = Date.now()
      // 如果token未过期，直接进入首页
      if (currentTime < accessExpiresIn) {
        uni.switchTab({
          url: '/pages/index/index'
        })
        return
      }
    }
    
    // 未登录时提前获取code
    this.getLoginCode()
  },
  
  methods: {
    // 检查手机号格式
    checkPhoneFormat() {
      const reg = /^1[3-9]\d{9}$/
      this.canLogin = reg.test(this.phone)
    },
    
    // 获取登录code
    async getLoginCode() {
      try {
        this.code = await getWxLoginCode()
      } catch (error) {
        uni.showToast({
          title: error.message,
          icon: 'none'
        })
      }
    },
    
    // 提交登录
    async submitLogin() {
      if (!this.code) {
        try {
          this.code = await getWxLoginCode()
        } catch (error) {
          uni.showToast({ title: error.message, icon: 'none' })
          return
        }
      }
    
      this.isLoading = true
      try {
        const loginRes = await login(this.phone, this.code)
        
        if (loginRes.code === 0) {
          // 登录成功，存储相关信息
          const { accessToken, refreshToken, accessExpiresIn, refreshExpiresIn, openIdMini, id } = loginRes.data
          // 存储token信息
          uni.setStorageSync('accessToken', accessToken)
          uni.setStorageSync('refreshToken', refreshToken)
          uni.setStorageSync('accessExpiresIn', accessExpiresIn.toString())
          uni.setStorageSync('refreshExpiresIn', refreshExpiresIn.toString())
          uni.setStorageSync('openIdMini', openIdMini)
          uni.setStorageSync('userId', id)
          
          // 简单的用户信息构造
          const userInfo = {
            id,
            openIdMini,
            // 可以根据实际情况补充其他用户信息
          }
          uni.setStorageSync('userInfo', userInfo)
          
          uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500,
            success: () => {
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/index/index'
                })
              }, 1500)
            }
          })
        } else {
          throw new Error(loginRes.message || '登录失败')
        }
      } catch (error) {
        console.error('登录失败:', error)
        uni.showToast({ title: error.message || '登录失败', icon: 'none' })
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  padding: 60rpx 40rpx;
  text-align: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #1b9a7c 0%, #2daf8b 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.login-title {
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  color: white;
}

.login-desc {
  margin-bottom: 80rpx;
  color: rgba(255,255,255,0.9);
  font-size: 28rpx;
}

.form-container {
  width: 100%;
  margin-bottom: 60rpx;
}

.input-item {
  width: 100%;
  height: 90rpx;
  background-color: rgba(255,255,255,0.9);
  border-radius: 45rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
}

.phone-input {
  flex: 1;
  height: 100%;
  font-size: 32rpx;
  color: #333;
  background: transparent;
}

.login-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 34rpx;
  background-color: rgba(255,255,255,0.9);
  color: #1b9a7c;
  border-radius: 45rpx;
  font-weight: bold;
}

.login-btn:disabled {
  background-color: rgba(255,255,255,0.5);
  color: #999;
}

.loading {
  margin-top: 30rpx;
  color: white;
  font-size: 28rpx;
}
</style>